package com.jt.common.filter;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

//过滤器(特殊拦截器)
interface  Filter{
    boolean invoke();
}
//控制器(负责请求分发)
interface  Servlet{
    void dispatch();
}
//过滤链
class FilterChain{
    private  List<Filter> filters=new CopyOnWriteArrayList<>();//过滤器(请求数据过滤)
    private Servlet servlet;//控制器(请求控制逻辑)
    public FilterChain(List<Filter> filters, Servlet servlet) {
        this.filters.addAll(filters);
        this.servlet = servlet;
    }
    public void doFilter(){//执行过滤链
        //请求过滤
        for(int i=0;i<filters.size();i++){
            if(!filters.get(i).invoke())return;
        }
        //请求分发
        servlet.dispatch();
    }
}
public class FilterChainTests {
    public static void main(String[] args) {
        //1.构建过滤器对象
        Filter filter1=new Filter() {
            @Override
            public boolean invoke() {
                System.out.println("filter 01");
                return true;
            }
        };
        Filter filter2=new Filter() {
            @Override
            public boolean invoke() {
                System.out.println("filter 02");
                return true;
            }
        };
        List<Filter> filters=new CopyOnWriteArrayList<>();
        filters.add(filter1);
        filters.add(filter2);
        //2.构建控制器对象
        Servlet servlet=new Servlet() {
            @Override
            public void dispatch() {
                System.out.println("将请求分发给具体对象去执行");
            }
        };
        //3.执行请求过滤及处理
        FilterChain fc=new FilterChain(filters,servlet);
        fc.doFilter();
    }
}
